from django.db import models
from django.conf import settings
from cloudinary.models import CloudinaryField


class UserPoints(models.Model):
    """用户积分"""
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='points', verbose_name='用户')
    total_points = models.IntegerField(default=0, verbose_name='总积分')
    available_points = models.IntegerField(default=0, verbose_name='可用积分')
    used_points = models.IntegerField(default=0, verbose_name='已使用积分')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'user_points'
        verbose_name = '用户积分'
        verbose_name_plural = '用户积分'
    
    def __str__(self):
        return f"{self.user.username} - {self.available_points}积分"


class PointsRecord(models.Model):
    """积分记录"""
    TYPE_CHOICES = (
        ('activity_create', '创建活动'),
        ('activity_join', '参加活动'),
        ('activity_join_cancel', '取消报名'),
        ('activity_checkin', '活动签到'),
        ('comment', '发表评论'),
        ('rating', '评分活动'),
        ('exchange', '积分兑换'),
        ('admin_adjust', '管理员调整'),
    )
    
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='points_records', verbose_name='用户')
    points = models.IntegerField(verbose_name='积分变动')
    type = models.CharField(max_length=30, choices=TYPE_CHOICES, verbose_name='类型')
    description = models.CharField(max_length=200, verbose_name='描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    # 关联活动ID，用于追踪每个活动的评论积分
    activity_id = models.IntegerField(null=True, blank=True, verbose_name='关联活动ID')
    
    class Meta:
        db_table = 'points_records'
        verbose_name = '积分记录'
        verbose_name_plural = '积分记录'
        ordering = ['-created_at']
        # 添加唯一约束：每个用户对每个活动的评论积分只能获得一次
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'activity_id', 'type'],
                condition=models.Q(type='comment'),
                name='unique_comment_points_per_activity'
            )
        ]
    
    def __str__(self):
        return f"{self.user.username} - {self.points}积分 - {self.get_type_display()}"


class Reward(models.Model):
    """奖励商品"""
    TYPE_CHOICES = (
        ('coupon', '优惠券'),
        ('privilege', '平台特权'),
        ('physical', '实物奖品'),
    )
    
    name = models.CharField(max_length=100, verbose_name='奖品名称')
    description = models.TextField(verbose_name='奖品描述')
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, verbose_name='类型')
    points_required = models.IntegerField(verbose_name='所需积分')
    stock = models.IntegerField(verbose_name='库存数量')
    # 奖品图片 - 使用Cloudinary存储
    image = CloudinaryField(
        '奖品图片',
        folder='rewards',
        null=True,
        blank=True,
        transformation={
            'width': 400,
            'height': 300,
            'crop': 'fill'
        }
    )
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'rewards'
        verbose_name = '奖励商品'
        verbose_name_plural = '奖励商品'
    
    def __str__(self):
        return self.name


class RewardExchange(models.Model):
    """奖励兑换记录"""
    STATUS_CHOICES = (
        ('pending', '待处理'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    )
    
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='exchanges', verbose_name='用户')
    reward = models.ForeignKey(Reward, on_delete=models.CASCADE, verbose_name='奖品')
    points_used = models.IntegerField(verbose_name='使用积分')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='兑换时间')
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')
    
    class Meta:
        db_table = 'reward_exchanges'
        verbose_name = '奖励兑换记录'
        verbose_name_plural = '奖励兑换记录'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.user.username} - {self.reward.name}"
